//
//  BridgeWebViewController.m
//  WebViewTest
//
//  Created by sank zhang on 2018/12/28.
//  Copyright © 2018年 sank zhang. All rights reserved.
//

#import "BridgeWebViewController.h"
#import "WebViewJavascriptBridge.h"
#import "MJExtension.h"

@interface BridgeWebViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) WebViewJavascriptBridge* bridge;
@property (nonatomic, strong) UIWebView* webView;
@end

@implementation BridgeWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.webView];
    
    [WebViewJavascriptBridge enableLogging];
    [self loadExamplePage];
    [self registerOCHandler];
}

//注册OC方法，提供给H5调用
- (void)registerOCHandler
{
    //注册一个testObjcCallback方法，给js调用
    //data:js方法传过来的数据
    //responseCallback:回调js
    //bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
    //    log('JS got response', response)
    //})
    [self.bridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:[data mj_JSONData] options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"----%@",dataDic);
        responseCallback(@"Response from testObjcCallback");
    }];
}

//OC调用js注册的testJavascriptHandler方法
- (void)callHandler
{
    id data = @{ @"greetingFromObjC": @"Hi there, JS!" };
    [self.bridge callHandler:@"testJavascriptHandler" data:data responseCallback:^(id response) {
        NSLog(@"testJavascriptHandler responded: %@", response);
    }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self callHandler];
}

- (void)loadExamplePage
{
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [self.webView loadHTMLString:appHtml baseURL:baseURL];
}

- (UIWebView *)webView
{
    if (_webView == nil) {
        _webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    }
    return _webView;
}

- (WebViewJavascriptBridge *)bridge
{
    if (_bridge == nil) {
        _bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
        [_bridge setWebViewDelegate:self];
    }
    return _bridge;
}
@end
